package com.shopping.mall.core.module.goods.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shopping.mall.auth.annotation.UnLogin;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.core.module.goods.entity.Goods;
import com.shopping.mall.core.module.goods.mapper.GoodsMapper;
import com.shopping.mall.core.module.goods.service.GoodsService;
import com.shopping.mall.core.module.goods.vo.GoodsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "商品")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private Logger logger;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private RedisTemplate<String, Goods> goodsRedisTemplate;

    @PutMapping("/changeGoodsSubImages")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    public Result<Object> changeGoodsSubImages(@RequestBody Goods goods){
        final List<String> subImageList = goods.getSubImageList();
        final String subImages = JSON.toJSONString(subImageList);
        Goods selectById = goodsMapper.selectById(goods.getId());
        selectById.setSubImages(subImages);
        goodsMapper.updateById(selectById);
        return Result.OK();
    }

    @ApiOperation("获取随机商品")
    @UnLogin
    @GetMapping("/getRandomGoods")
    public Result<Object> getRandomGoods(@RequestParam Integer n, HttpServletRequest request) {
        return goodsService.getRandomGoods(n, request);
    }

    @ApiOperation("按type查询(筛选)商品,分页返回")
    @GetMapping("/filtrateByType")
    @UnLogin
    public Result<Object> filtrateByType(
            @RequestParam(required = false) String typeId,
            @RequestParam(name = "current", defaultValue = "1") Integer current,
            @RequestParam(name = "size", defaultValue = "10") Integer size,
            @RequestParam(required = false) String text,
            HttpServletRequest request) {
        return goodsService.filtrateByType(typeId, current, size, text, request);
    }

    @ApiOperation("管理员按type查询(筛选)商品,分页返回")
    @GetMapping("/filtrateByTypeAdmin")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    public Result<Object> filtrateByTypeAdmin(
            @RequestParam(required = false) String typeId,
            @RequestParam(name = "current", defaultValue = "1") Integer current,
            @RequestParam(name = "size", defaultValue = "10") Integer size,
            @RequestParam(required = false) String text) {
        goodsService.filtrateByTypeAdmin(typeId, current, size, text);
        return goodsService.filtrateByTypeAdmin(typeId, current, size, text);
    }

    @ApiOperation("按type查询(筛选)商品,不分页")
    @GetMapping("/filtrateByTypeNoPage")
    @UnLogin
    public Result<Object> filtrateByType(@RequestParam(required = false) String typeId,
                                         @RequestParam(required = false) String text,
                                         HttpServletRequest request) {
        return goodsService.filtrateByType(typeId, text, request);
    }

    @ApiOperation("商品信息")
    @GetMapping("goodsInfo")
    @UnLogin
    public Result<Object> goodsInfo(@RequestParam String id, HttpServletRequest request) {
        return goodsService.goodsInfo(id, request);
    }

    @ApiOperation("分页查询")
    @GetMapping("/page")
    @UnLogin
    public Result<IPage<Goods>> getGoodsPage(
            @RequestParam(name = "current", defaultValue = "1") Integer current,
            @RequestParam(name = "size", defaultValue = "10") Integer size,
            Goods goods) {
        IPage<Goods> goodsPage = goodsService.getGoodsPage(current, size, goods);
        return Result.OK(goodsPage);
    }

    @ApiOperation("修改")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    @PutMapping
    public Result<Object> update(@Validated(Goods.update.class) @RequestBody Goods goods) {
        try {
            return goodsService.changeGoods(goods);
        } catch (RuntimeException e) {
            logger.error("事务异常,终止操作:{}", e.getStackTrace());
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("修改状态")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    @PutMapping("/updateStatus")
    public Result<Object> updateStatus(@Validated(Goods.update.class) @RequestBody Goods goods) {
        return goodsService.changeGoodsStatus(goods);
    }

    @ApiOperation("新增")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    @PostMapping
    public Result<Object> add(@Validated(Goods.insert.class) @RequestBody Goods goods) {
        try {
            return goodsService.add(goods);
        } catch (RuntimeException e) {
            logger.error("事务异常,终止操作:{}", e.getStackTrace());
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("商品和规格一起添加")
    @PostMapping("/addGoodsWithSpecification")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    public Result<Object> addGoodsWithSpecification(@RequestBody GoodsVo goodsVo) {
        try {
            System.out.println(goodsVo.toString());
            return goodsService.addGoodsWithSpecification(goodsVo);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("通过id查询")
    @GetMapping("/id")
    @UnLogin
    public Result<Goods> getById(@RequestParam String id) {
        Goods goods = goodsRedisTemplate.opsForValue().get(id);
        if(goods==null){
            goods = goodsService.getById(id);
            goodsRedisTemplate.opsForValue().set(id,goods,1, TimeUnit.HOURS);
        }
        return Result.OK(goods);
    }

    @ApiOperation("查询所有")
    @GetMapping
    @UnLogin
    public Result<List<Goods>> getAll(Goods goods) {
        List<Goods> goodsList = goodsService.getAll(goods);
        return Result.OK(goodsList);
    }

    @ApiOperation("通过id删除")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    @DeleteMapping("/id")
    public Result<Object> deleteById(@RequestParam String id) {
        return goodsService.deleteById(id);
    }

    @ApiOperation("批量删除")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NORMAL_ADMIN')")
    @DeleteMapping("/batch")
    public Result<Object> batchDelete(@RequestParam List<String> ids) {
        return goodsService.batchDelete(ids);
    }


}
